package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.POJO.Permission;
import com.itheima.POJO.Role;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.service.RoleService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/role")
public class RoleController {
    @Reference
    private RoleService roleService;

    @RequestMapping("/findAllRole")
    public Result findAllRole(){
        Result result = roleService.findAllRole();
        return result;
    }


    @PreAuthorize("hasAuthority('ROLE_QUERY')")
    @RequestMapping("/getrole")
    public Result getrole(@RequestBody Map map){
        try {
            PageResult pageResult=roleService.getrole(map);
            return new Result(true,"查询角色成功",pageResult);
        } catch (Exception e) {
            return new Result(false,"查询角色失败");
        }
    }

    @RequestMapping("/getpermissions")
    public Result getpermissions(){
        try {
            List<Permission>list=roleService.getpermissions();
            return new Result(true,"查询权限成功",list);
        } catch (Exception e) {
            return new Result(false,"查询权限失败");
        }
    }

    @RequestMapping("/addrole")
    @PreAuthorize("hasAuthority('ROLE_ADD')")
    public Result addrole(Integer[] checkitemIds,@RequestBody Role role){
        try {
            List<Permission>list=roleService.addrole(checkitemIds,role);
            return new Result(true,"增加角色成功",list);
        } catch (Exception e) {
            return new Result(false,"增加角色失败");
        }
    }

    @RequestMapping("/delete")
    @PreAuthorize("hasAuthority('ROLE_DELETE')")
    public Result delete(Integer id){
        try {
            roleService.deleteRole(id);
            return new Result(true,"删除角色成功");
        } catch (Exception e) {
            return new Result(false,"删除角色失败");
        }
    }

    @RequestMapping("/findRoleById")
    public Result findRoleById(Integer id){
        try {
            Role role=roleService.findRoleById(id);
            return new Result(true,"编辑查询角色成功",role);
        } catch (Exception e) {
            return new Result(false,"编辑查询角色失败");
        }
    }
    @RequestMapping("/edit")
    @PreAuthorize("hasAuthority('ROLE_EDIT')")
    public Result edit(Integer[] checkitemIds,@RequestBody Role role ){
        try {
            roleService.edit(checkitemIds,role);
            return new Result(true,"编辑查询角色成功");
        } catch (Exception e) {
            return new Result(false,"编辑查询角色失败");
        }
    }
}
